<template>
  <div class="chart" ref="chartRef"></div>
</template>

<script setup>
import { markRaw, watch, onBeforeUnmount, onMounted, ref } from "vue";
import * as echarts from "echarts";
import "echarts-wordcloud";

const props = defineProps({
  chartOptions: {
    type: Object,
    default: () => ({}),
  },
});

const loading = ref(true);

const emits = defineEmits(["chartParamClick"]);

watch(
  () => props.chartOptions,
  (nv, ov) => {
    console.log(nv, ov);
    loading.value = true;
    init();
  },
  {
    deep: true,
  }
);

let chartRef = ref(null);
let myChartRef = ref(null);
let commonOptions = ref({});
const options = ref({ ...commonOptions.value, ...props.chartOptions });

function init() {
  if (!chartRef.value) return;
  loading.value = true;
  myChartRef.value?.dispose();
  myChartRef.value = echarts.getInstanceByDom(chartRef.value);
  if (!myChartRef.value) {
    myChartRef.value = markRaw(
      echarts.init(chartRef.value, "light", {
        renderer: "canvas",
      })
    );
  }
  setEcharts();
}

onMounted(() => {
  init();
  window.addEventListener("resize", () => {
    myChartRef.value.resize();
  });
});

onBeforeUnmount(() => {
  myChartRef.value?.dispose();
  window.removeEventListener("resize", myChartRef.value);
});

function setEcharts() {
  if (myChartRef.value) {
    myChartRef.value.setOption(options.value);
  }
}

defineExpose({
  init,
  setEcharts,
  loading,
});
</script>

<style scoped lang="less">
.chart {
  min-width: 400px;
  min-height: 128px;
  height: 100%;
  width: 100%;
}
</style>
